from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QLineEdit, QMessageBox
from PyQt5.QtCore import Qt
from PyQt5 import QtGui
import cv2
import fastdeploy as fd
import load
import interface
import sys
import os
import datetime


class LoginWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.m_Position = None
        self.m_flag = None
        self.ui = load.Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.ui.pushButton.clicked.connect(self.go_to_inter)
        self.ui.lineEdit_2.setEchoMode(QLineEdit.Password)
        self.show()

    def go_to_inter(self):
        account = self.ui.lineEdit.text()
        password = self.ui.lineEdit_2.text()
        if account == "admin" and password == "woshiniba":
            InterWindow()
            self.close()
        else:
            QMessageBox.warning(self, '警告', '密码错误', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

    # 拖动
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton and self.isMaximized() == False:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
            event.accept()
            self.setCursor(QtGui.QCursor(Qt.OpenHandCursor))  # 更改鼠标图标

    def mouseMoveEvent(self, mouse_event):
        if Qt.LeftButton and self.m_flag:
            self.move(mouse_event.globalPos() - self.m_Position)  # 更改窗口位置
            mouse_event.accept()

    def mouseReleaseEvent(self, mouse_event):
        self.m_flag = False
        self.setCursor(QtGui.QCursor(Qt.ArrowCursor))


class InterWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.m_Position = None
        self.m_flag = None
        self.ui = interface.Ui_MainWindow_inter()
        self.ui.setupUi(self)
        self.setWindowFlag(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.ui.pushButton_img.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(0))  # stackWidget切换页面
        self.ui.pushButton_imgpack.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(1))
        self.ui.pushButton_set.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(2))
        self.ui.pushButton_maxsize.clicked.connect(self.resize_Win)
        self.ui.pushButton_browse.clicked.connect(self.open_file)
        self.ui.pushButton_browse_2.clicked.connect(self.open_file_2)
        self.ui.horizontalSlider.setRange(0, 100)
        self.ui.horizontalSlider.setValue(70)
        self.ui.horizontalSlider.setPageStep(10)
        self.ui.lineEdit_2.setText("0.7")
        self.ui.horizontalSlider.valueChanged.connect(self.updata_lineEditText)
        self.ui.lineEdit_2.setInputMask("0.00")
        self.ui.lineEdit_2.textChanged.connect(self.updata_SliderValue)
        self.ui.pushButton_run.clicked.connect(self.img_modelrun)
        self.ui.label.setScaledContents(True)
        self.show()
        # 更新进度条数值

    # 模型推理
    def img_modelrun(self):
        if len(self.ui.lineEdit.text()) != 0:
            model = fd.vision.classification.PaddleClasModel(
                model_file='./model/inference.pdmodel',
                params_file='./model/inference.pdiparams',
                config_file='./model/inference_cls.yaml',
            )
            print(self.ui.pushButton_browse.fileName)
            img = cv2.imread(self.ui.pushButton_browse.fileName)
            result = model.predict(img)
            time = datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]' + "[INFO:]")
            self.ui.textBrowser.append(time + str(result))  # 在指定的区域显示提示信息
            labelId = result.label_ids[0]
          #  with open("./model/label_list.txt", 'r') as o:
          #      labelmap = o.readline()
           # label = labelmap[labelId].replace('\n', '')



        else:
            QMessageBox.warning(self, '警告', '输入错误', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

    def updata_SliderValue(self):
        i = float(self.ui.lineEdit_2.text())
        if 1 >= i >= 0:
            print("i=", i * 100)
            i = i * 100
            self.ui.horizontalSlider.setValue(int(i))
        else:
            print("error")
            QMessageBox.warning(self, '警告', '输入错误', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

    def open_file(self):
        self.ui.pushButton_browse.fileName, self.ui.pushButton_browse.fileType = QFileDialog.getOpenFileName(self,
                                                                                                             "选取文件",
                                                                                                             os.getcwd(),
                                                                                                             "All Files(*);;Image Files(*.png *.jpeg)")
        self.ui.lineEdit.setText(self.ui.pushButton_browse.fileName)
        pix = QtGui.QPixmap(self.ui.pushButton_browse.fileName)
        self.ui.label.setPixmap(pix)
        self.ui.label.setStyleSheet("border: 2px solid blue")
        self.ui.label.setScaledContents(True)

    def open_file_2(self):
        self.ui.pushButton_browse_2.directory = QFileDialog.getExistingDirectory(self, "getExistingDirectory", "./")
        self.ui.lineEdit_3.setText(self.ui.pushButton_browse_2.directory)

    # 更新lineedit数值
    def updata_lineEditText(self):
        print(self.ui.horizontalSlider.value() / 100)
        self.ui.lineEdit_2.setText(str(self.ui.horizontalSlider.value() / 100))

    def resize_Win(self):
        if self.isMaximized():
            self.showNormal()
            self.ui.pushButton_maxsize.setStyleSheet("QPushButton{\n"
                                                     "    \n"
                                                     "    \n"
                                                     "    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(0, 0, 255, 255), stop:1 rgba(255, 255, 255, 255));\n"
                                                     "    border-radius:15px;\n"
                                                     "    min-width: 30px; \n"
                                                     "    max-width: 30px;\n"
                                                     "    min-height: 30px; \n"
                                                     "    max-height: 30px;\n"
                                                     "}\n"
                                                     "\n"
                                                     "QPushButton:hover{\n"
                                                     "    \n"
                                                     "    \n"
                                                     "    border-image: url(:/icon/icon/全局放大2_full-screen-two.svg);\n"
                                                     "}\n"
                                                     "")
        else:
            self.showMaximized()
            self.ui.pushButton_maxsize.setStyleSheet("QPushButton{\n"
                                                     "    \n"
                                                     "    \n"
                                                     "    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1, stop:0 rgba(0, 0, 255, 255), stop:1 rgba(255, 255, 255, 255));\n"
                                                     "    border-radius:15px;\n"
                                                     "    min-width: 30px; \n"
                                                     "    max-width: 30px;\n"
                                                     "    min-height: 30px; \n"
                                                     "    max-height: 30px;\n"
                                                     "}\n"
                                                     "\n"
                                                     "QPushButton:hover{\n"
                                                     "    \n"
                                                     "    \n"
                                                     "    border-image: url(:/icon/icon/全局缩小_off-screen.svg);\n"
                                                     "}\n"
                                                     "")
        # 拖动

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton and self.isMaximized() == False:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
            event.accept()
            self.setCursor(QtGui.QCursor(Qt.OpenHandCursor))  # 更改鼠标图标

    def mouseMoveEvent(self, mouse_event):
        if Qt.LeftButton and self.m_flag:
            self.move(mouse_event.globalPos() - self.m_Position)  # 更改窗口位置
            mouse_event.accept()

    def mouseReleaseEvent(self, mouse_event):
        self.m_flag = False
        self.setCursor(QtGui.QCursor(Qt.ArrowCursor))


if __name__ == "__main__":
    app = QApplication([])
    app.setWindowIcon(QtGui.QIcon("./eyes.png"))
    win = InterWindow()
    sys.exit(app.exec_())
